﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MWS.Processing.Interfaces;

namespace MWS.Processing.Processors
{
    public abstract class EnqueueProcessor<TRequest, TResponse, TQueueRequest> :
        QueueProcessor<TRequest, TResponse, TQueueRequest> where TRequest : class
    {
        protected EnqueueProcessor(Func<TRequest, TResponse> operation, IQueue<TQueueRequest> queue)
            : base(operation, queue)
        {
        }

        public override void OnProcessComplete(object sender, ResponseEventArgs args)
        {
            var queueRequests = GetQueueRequests(args.Request, args.Response);
            Parallel.ForEach(queueRequests,
                             new ParallelOptions {MaxDegreeOfParallelism = ProcessRequestsMaxParallel},
                             queueRequest =>
                             Queue.Enqueue(queueRequest));
        }

        public abstract IList<TQueueRequest> GetQueueRequests(TRequest request, TResponse response);
    }
}